import { useState } from 'react';
import {message, Upload, UploadFile, UploadProps} from 'antd'
import { observer } from 'mobx-react'
import userStore from "@/store/userStore.ts";
import { uploadProfile } from '@/api/upload.ts'
import styles from './uploadFile.module.scss'

const UploadFileComponent = () => {
    const [fileList, setFileList] = useState<Array<UploadFile>>([])
    const customRequest = async (): Promise<void> => {
        const file = (fileList as Array<{ originFileObj: File }>)[0].originFileObj as File
        const data = new FormData()
        data.append('file', file)
        data.append('oldPath', userStore.oldProfile)
        const response = await uploadProfile(data)
        if (response.code === 200) {
            userStore.changeProfile(response.data.path)
            message.success('上传成功')
        } else {
            message.error('上传失败')
        }
        setFileList([])
    }
    const changeFile: UploadProps['onChange'] = (info) => {
        const { file } = info
        setFileList([file])
    }
    return (
        <div className={styles.uploadFile}>
            <Upload
                fileList={fileList}
                accept={import.meta.env.VITE_ACCEPT_IMAGE}
                name="avatar"
                listType="picture-circle"
                className="avatar-uploader"
                showUploadList={false}
                maxCount={1}
                onChange={changeFile}
                customRequest={customRequest}
            >
                {
                    userStore.user.profile ?
                    <img src={`/api${userStore.user.profile}`} alt="avatar" style={{width: '100%'}}/> :
                    <img src={`/api${import.meta.env.VITE_USER_PROFILE}`} alt="avatar" style={{width: '100%'}}/>
                }
            </Upload>
        </div>
    );
};

export default observer(UploadFileComponent)